# coding=utf8
import redis
from pymongo import MongoClient
from pymongo.collection import Collection
from libs import config

# 初始化mongo池
mongo_pool = {}
mongo_dbs_config = config['DataBase']['mongo']
for db_name in mongo_dbs_config:
    mongo_config = mongo_dbs_config[db_name]
    client = MongoClient(mongo_config['host'] + ':' + str(mongo_config['port']))
    db = client[mongo_config['database']]
    if 'user' in mongo_config.keys():
        db.authenticate(mongo_config['user'], mongo_config['password'])
    mongo_pool[db_name] = db


class MongoBase(Collection):
    def __init__(self, coll_name, db='default'):
        super(MongoBase, self).__init__(mongo_pool[db], coll_name)

    def get_list(self, limit, last_id=None, **kwargs):
        if last_id is not None:
            where = {
                '_id': {
                    '$gt': last_id
                }
            }
        else:
            where = {}
        if 'where' in kwargs:
            where.update(kwargs['where'])
        # todo 加入sort
        # sort = [{'_id': -1}]
        print(where)
        return self.find(where).limit(limit).sort('_id')


# 初始化redis
redis_config = config['DataBase']['redis']['default']
model_redis = redis.StrictRedis(host=redis_config['host'], port=redis_config['port'], decode_responses=True)

# 同意reids_key
CO_STATICS_RKEY = 'CO_STATICS:{keyword}'
